package com.luo.d3s.core.infrastructure.convertor;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luo.d3s.core.application.dto.PageQuery;
import com.luo.d3s.core.application.dto.PageResponse;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * PageHelper分页转换
 *
 * @author luohq
 * @date 2023-07-07
 */
public interface PageHelperConvertor {

    /**
     * PageQuery转换为PageHelper.startPage(...)
     *
     * @param pageQuery 分页查询参数
     */
    static void startPage(PageQuery pageQuery) {
        String orderBy = Stream.of(pageQuery.getOrderBy(), pageQuery.getOrderBy())
                .filter(Objects::nonNull)
                .collect(Collectors.joining(" "));
        PageHelper.startPage(pageQuery.getPageIndex(), pageQuery.getPageSize(), orderBy);
    }

    /**
     * 转换PageHelper分页查询结果为PageResponse
     *
     * @param pageInfo PageHelper分页查询结果
     * @param <T>      实体类型
     * @return PageResponse
     */
    static <T> PageResponse<T> toPageResponse(PageInfo<T> pageInfo) {
        return PageResponse.of(pageInfo.getList(),
                Long.valueOf(pageInfo.getTotal()).intValue(),
                pageInfo.getPageSize(),
                pageInfo.getPageNum());
    }

    /**
     * 转换PageHelper分页查询结果为PageResponse
     *
     * @param listResult PageHelper分页查询结果
     * @param <T>        实体类型
     * @return PageResponse
     */
    static <T> PageResponse<T> toPageResponse(List<T> listResult) {
        return toPageResponse(PageInfo.of(listResult));
    }

    /**
     * 转换PageHelper分页查询结果为PageResponse
     *
     * @param pageInfo  PageHelper分页查询结果
     * @param convertor 实体转换器
     * @param <T>       源实体类型
     * @param <R>       目标实体类型
     * @return PageResponse
     */
    static <T, R> PageResponse<R> toPageResponse(PageInfo<T> pageInfo, Function<T, R> convertor) {
        List<R> resultList = Collections.emptyList();
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            resultList = pageInfo.getList().stream()
                    .map(convertor)
                    .collect(Collectors.toList());
        }
        return PageResponse.of(resultList,
                Long.valueOf(pageInfo.getTotal()).intValue(),
                pageInfo.getPageSize(),
                pageInfo.getPageNum());
    }

    /**
     * 转换PageHelper分页查询结果为PageResponse
     *
     * @param listResult PageHelper分页查询结果
     * @param convertor  实体转换器
     * @param <T>        源实体类型
     * @param <R>        目标实体类型
     * @return PageResponse
     */
    static <T, R> PageResponse<R> toPageResponse(List<T> listResult, Function<T, R> convertor) {
        return toPageResponse(PageInfo.of(listResult), convertor);
    }
}
